package it.softphone.commons.spring.config.plugin;

import java.lang.annotation.Annotation;

import org.springframework.beans.factory.HierarchicalBeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultBeanNameGenerator;
import org.springframework.config.java.plugin.ConfigurationPlugin;

abstract class AbstractBaseConfigResourceHandler<A extends Annotation> implements ConfigurationPlugin<A> {

    public final void handle(A annotation, BeanDefinitionRegistry registry) {
        BeanDefinition beanDef = doHandle(annotation, registry);

        // workaround related to hidden beans
        if(registry instanceof HierarchicalBeanFactory)
            if(((HierarchicalBeanFactory)registry).getParentBeanFactory() instanceof BeanDefinitionRegistry)
                registry = (BeanDefinitionRegistry)((HierarchicalBeanFactory)registry).getParentBeanFactory();

        // generate a unique bean name for this resolver
        String beanName = new DefaultBeanNameGenerator().generateBeanName(beanDef, registry);

        registry.registerBeanDefinition(beanName, beanDef);
    }

    abstract BeanDefinition doHandle(A annotation, BeanDefinitionRegistry registry);
}
